package com.white.algebra.controller;

import com.white.algebra.domain.Discuss;
import com.white.algebra.domain.Discussion;
import com.white.algebra.domain.Pager;
import com.white.algebra.domain.Syslog;
import com.white.algebra.service.DiscussService;
import com.white.algebra.service.impl.DiscussServiceImpl;
import com.white.algebra.utils.WebUtils;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Date;
import java.util.List;
@MultipartConfig    //标识Servlet支持文件上传
public class DiscussController extends BaseServlet{
    private DiscussService discussService=new DiscussServiceImpl();
    protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        int page= WebUtils.parseInt(req.getParameter("page"),1);
        int size= WebUtils.parseInt(req.getParameter("size"),10);
        if(page<1){
            page=1;
        }
        String name = req.getParameter("name");
        int startRecord=(page-1)*size;
        List<Discussion> discussionList=discussService.findAll( startRecord,  size, name);
        int recordCount=discussService.getDiscussionNum(name);
        Pager<Discussion> pager=new Pager<>();
        pager.calculate(discussionList,page,size,recordCount);
        req.setAttribute("page",pager);
        req.setAttribute("name",name);
        req.getRequestDispatcher("/pages/discussion-list.jsp").forward(req,resp);
    }
    protected void insertDiscussion(HttpServletRequest req,HttpServletResponse resp) throws IOException, SQLException {
        String author=req.getParameter("author");
        String name=req.getParameter("name");
        String text=req.getParameter("text");
        Discussion discussion=new Discussion();
        discussion.setAuthor(author);
        discussion.setName(name);
        discussion.setText(text);
        discussion.setTime(new Date());
        discussService.insertDiscussion(discussion);
        resp.sendRedirect(req.getContextPath()+"/discuss?action=findAll");
    }
    protected void findDiscussionById(HttpServletRequest req,HttpServletResponse resp) throws Exception {
        String id=req.getParameter("id");
        int page= WebUtils.parseInt(req.getParameter("page"),1);
        int size= WebUtils.parseInt(req.getParameter("size"),10);
        if(page<1){
            page=1;
        }
        int startRecord=(page-1)*size;
        Discussion discussion=discussService.findDiscussionById(id,startRecord,size);
        int recordCount=discussService.getDiscussNum(discussion.getId());
        Pager<Discuss> pager=new Pager<>();
        pager.calculate(discussion.getDiscuss(),page,size,recordCount);
        req.setAttribute("page",pager);
        req.setAttribute("discussion",discussion);
        req.getRequestDispatcher("/pages/discussion-show.jsp").forward(req,resp);
    }
    protected void thumbUp(HttpServletRequest req,HttpServletResponse resp){
        String id=req.getParameter("id");
        String fun=req.getParameter("fun");
        //t 点赞   f 去赞
        discussService.thumbUp(id,fun);
    }
    protected void insertDiscuss(HttpServletRequest req,HttpServletResponse resp) throws IOException, SQLException {
        String author=req.getParameter("author");
        String discussId=req.getParameter("discussId");
        String discussionId=req.getParameter("discussionId");
        String text=req.getParameter("text");
        Discuss discuss=new Discuss();
        discuss.setAuthor(author);
        discuss.setDiscussId(discussId);
        discuss.setDiscussionId(discussionId);
        discuss.setText(text);
        discuss.setTime(new Date());
        discussService.insertDiscuss(discuss);
    }
    protected void imageUpload(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException {
        JSONObject res = new JSONObject();
        resp.setContentType("text/html;charset=utf-8");

        String savePath = req.getServletContext().getRealPath("/uploadFile");  //存储路径
        File path = new File(savePath);
        if (!path.exists()) { //如果路径不存在则创建
            path.mkdirs();
        }

        Collection<Part> parts = req.getParts(); //获取上传的文件集合
        if (parts != null && parts.size() == 1) {   //上传单个文件
            Part part = req.getPart("editormd-image-file"); //-----① 通过表单file控件(<input type="file" name="file">)的名字直接获取Part对象
            String header = part.getHeader("content-disposition");//获取请求头
            String fileName = getFileName(header);
            String url = savePath + File.separator + fileName;
            part.write(url);           //把文件写到指定路径
            String thepath = req.getContextPath();
            String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+thepath+"/uploadFile/"+fileName;
            res.put("success", 1);
            res.put("message", "上传成功");
            res.put("url", basePath);
        } else {
            res.put("success", 0);
            res.put("message", "上传失败");
        }


        PrintWriter out = resp.getWriter();
        out.println(res.toString());
        out.flush();
        out.close();
    }
    public String getFileName(String header) {
        String[] temp = header.split(";")[2].split("=");
        //获取文件名，兼容各种浏览器的写法
        String fileName = temp[1].substring(temp[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
        return fileName;
    }
}
